import 'package:flutter/material.dart';
import 'package:flutter_app/model/video_model.dart';
import 'package:flutter_app/page/home_page.dart';
import 'package:flutter_app/page/video_details_page.dart';
import 'package:flutter_app/route/route_path.dart';

class BiliRouterDelegate extends RouterDelegate<BiliRoutePath>
    with ChangeNotifier, PopNavigatorRouterDelegateMixin {

  final GlobalKey<NavigatorState> navigatorKey;

  ///为Navigator设置一个key，必要时候可以通过navigatorkey。currentState来获取 NavigatorState对象
  BiliRouterDelegate() : navigatorKey = GlobalKey<NavigatorState>();

  ///
  List<MaterialPage> page = [];
  VideoModel _videoModel;
  BiliRoutePath path;
  @override
  Widget build(BuildContext context) {
    page=[
      pageWra(HomePage(
        onJumpToDetail: (videoModel){
          _videoModel=videoModel;
          notifyListeners();
      },)),
      if(_videoModel!=null)pageWra(VideoPage(videoModel: _videoModel)),
    ];
    //构建路由堆栈
    return Navigator(
      key: navigatorKey,
      pages: page,
      onPopPage: (route, result) {
        ///这里判断是否可以返回
        if (!route.didPop(result)) {
          return false;
        }
        return true;
      },
    );
  }

  @override
  Future<void> setNewRoutePath(BiliRoutePath configuration) async {
    path=configuration;
  }

}

///可缺省，主要应用于web、持有
class BiliRouterInfoMationParser extends RouteInformationParser<BiliRoutePath> {
  @override
  Future<BiliRoutePath> parseRouteInformation(
      RouteInformation routeInformation) async {
    final uri = Uri.parse(routeInformation.location);
    print("uri:$uri");
    if (uri.pathSegments.isEmpty) {
      return BiliRoutePath.home();
    }
    return BiliRoutePath.detail();
  }
}

pageWra(Widget child){
  return MaterialPage(child: child,key: ValueKey(child.hashCode));
}